﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StreamDemo.aspx.cs" 
	MasterPageFile="~/Site.master" Inherits="HoneyBadgersOfficePlayer.Views.StreamDemo" %>


<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<link href="./../JPlayerSkins/midnight.black/jplayer.midnight.black.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript" src="./../JPlayerJS/jquery.jplayer.min.js"></script> <!-- where jplayer is located -->
<script type="text/javascript">
//<![CDATA[    
	var roomAdmin = false;              // lets the client know if they are actively grabbing songs or listening for them
    var roomID = <%= roomID %>;
    var userID = <%= userID %>;    
    var songID = 0;    
	checkMasterUser();                  // checks if they are the master user of the room
	var roomStatus = "Play";            // default room status for playback
	intervalThreeSeconds = setInterval(checkRoomStatus, 3000); // checks roomstatus every 3 seconds
    intervalTenSeconds = setInterval(updateRoomData, 10000); // updates room data every 10 seconds        
	
	$(document).ready(function () {     // when the page is ready load up jplayer
		$("#jquery_jplayer_1").jPlayer(
		{
			ready: function () { 
				if (roomAdmin == true) { // if we are room admin we will grab the next song dynamically
					var songData = getNewSong();                    

                    // Data Key ["File_location"]["Artist"]["Song Name"]["Duration"]["Song_ID"]
					var string = songData.split('|');
					$('#artist').html(string[1]);
					$('#songname').html(string[2]);
                    songID = string[4];
                    getAvgRating();
                    updateSongHistoryTable(songID);
                    updateRoomSong(0);
					$(this).jPlayer("setMedia", { mp3: string[0] }).jPlayer("play");                    
				}
				else {  // we just listen for the next song and start playing it
					var songData = getCurrentSong();

                    // ["File_location"]["Artist"]["Song Name"]["Duration"]["Song_ID"]["Song_Position"]                      
					var string = songData.split('|');
					$('#artist').html(string[1]);
					$('#songname').html(string[2]);
                    songID = string[4];   
                    getAvgRating();
					$(this).jPlayer("setMedia", { mp3: string[0] });
					$(this).jPlayer("play", parseInt(string[5])); // starts playing at the time of the song in the database                     
				}   
			},
			ended: function (event) {
				var songData = "";
				if (roomAdmin == true) { // if we are room admin we will grab the next song dynamically
				    songData = getNewSong();
				}
				else {  // we just listen for the next song and start playing it
				    songData = getCurrentSong();
				}
				var string = songData.split('|');
				$('#artist').html(string[1]);
				$('#songname').html(string[2]);
                songID = string[4];
                getAvgRating();                
                if (roomAdmin == true)
                {
                    updateSongHistoryTable(songID);
                    updateRoomSong(0);
                }
				$(this).jPlayer("setMedia", { mp3: string[0] }).jPlayer("play");                
			},
			swfPath: "./../JPlayerJS",
			solution: "html, flash", // use HTML5 first, with a Flash fallback 
			supplied: "mp3",
			wmode: "window"
		});
	});
           

    // master users call this to get a new song from the database
    function getNewSong()
    {           
        var songData = "";
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getNewSong",
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
            async: false,
			success: function (data) { songData = data.d + ""; } // gets the new song			
		});
        return songData;         
    }


    //gets average song rating for current song playing
    function getAvgRating()
    {
        var avgSongRating = "";
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getAvgSongRating",
			data: "{songID: '"+ songID +"', roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data){ 
                avgSongRating = data.d + "";
                $('#lblAvgRate').html("Average Song Rating: " + avgSongRating); 
            }
		});         
    }


    // regular users call this to get the song from the database that is currently playing in the room
    function getCurrentSong()
    {
        var songData = "";
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getCurrentSong",
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
            async: false,
			success: function (data) { songData = data.d + ""; } // gets the current song			
		});
        return songData;
    }


    function updateRoomSong(position)
    {
        // updateRoomSong to the database
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/updateRoomSong",
			data: "{userID: '"+ userID +"', songID: '"+ songID +"', secondsIntoSong: '"+ position +"', roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});
    }


    function updateSongHistoryTable(song)
    {
        // updateSongHistoryTable in the database
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/updateSongHistoryTable",
			data: "{roomID: '"+ roomID +"', songID: '"+ song +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});
    }


    // checks the server to see if they are the master user in the room
	function checkMasterUser()
    {        
		var masterUser = 0;

		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/checkMasterUser",
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) {
                masterUser = data.d; // gets the master user's ID
                if (masterUser == userID)            
			        roomAdmin = true;
		        else
			        roomAdmin = false; 
            }
		});                    
	}


	// this functions runs at a set interval of 3 seconds  
	function checkRoomStatus() 
    {
		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getRoomStatus",
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: handleResponseStatus // gets the global room status and sends it to the handle response status function			
		});
                
        if (roomAdmin == true)
        {
            var position = 0;
            position = getSongsCurrentTime();                
            updateRoomSong(position);   // updates the song position every three seconds
        }                   

        // Ajax call to update userHeartBeat
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/updateHeartBeats",
			data: "{roomID: '"+ roomID +"', userID: '"+ userID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});        
        
        getChatComments();
        getSongComment();
        getAvgRating();        
	}


    function updateRoomData()
    {   
        checkMasterUser();
        updateUserList();
        updateSongHistoryList();
        getUpdatedSongRating();        
    }


	function handleResponseStatus(data) {
		var responseStatus = data.d; // the .d is for data :)

		if (responseStatus == roomStatus) {     // do nothing, the status has not changed
			var d; // just some code :)
		}
		else if (responseStatus == "Pause") {   // someone paused so pause playback and set the new local status
			$("#jquery_jplayer_1").jPlayer("pause");
			roomStatus = "Pause";
		}
		else if (responseStatus == "Skip") {    // someone skipped a song so get the new song from the database
			var songData = getCurrentSong();
            var string = songData.split('|');
            $('#artist').html(string[1]);
            $('#songname').html(string[2]);
            songID = string[4];
            getAvgRating();
            $("#jquery_jplayer_1").jPlayer("setMedia", { mp3: string[0] }).jPlayer("play");
			roomStatus = "Skip";
		}
		else if (responseStatus == "Play") {    // playback is resumed, set our new local status
			$("#jquery_jplayer_1").jPlayer("play");
			roomStatus = "Play";
		}
		else
			alert("Unknown responseStatus");    // something bad happened :(
	}


    function updateRoomStatus(newStatus)
    {    
		$.ajax({            // dynamically sets the songStatus 
			type: "POST",
			url: "./../WebService/SongStatus.asmx/setRoomStatus",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			data:  "{roomID: '"+ roomID +"', songStatus: '"+ newStatus +"'}"
		});
              
		roomStatus = newStatus; // set the appropriate local roomStatus

        if(newStatus == 'Skip') // if the user presses the skip button
        {            
            var songData = getNewSong();    // we get a new song cause the last one sucked

            var string = songData.split('|');
		    $('#artist').html(string[1]);
		    $('#songname').html(string[2]);
            songID = string[4];
            getAvgRating();
            updateSongHistoryTable(songID);
		    $("#jquery_jplayer_1").jPlayer("setMedia", { mp3: string[0] }).jPlayer("play");

            setTimeout( function(){
                roomStatus = "Play";
                $.ajax({            // resets the global songStatus to play
			        type: "POST",
			        url: "./../WebService/SongStatus.asmx/setRoomStatus",
			        contentType: "application/json; charset=utf-8",
			        dataType: "json",
			        data:  "{roomID: '"+ roomID +"', songStatus: 'Play'}"
		        });
            }, 3000); // sets the status back to play after 3 seconds so we are not stuck in skip mode
        }
    }
    
    	
    // gets the song current time from the jplayer
    function getSongsCurrentTime()
    {
        var time = document.getElementById("currentTime").innerHTML;
        var splitTime = time.split(':');
        var minutes = parseInt(splitTime[0]);
        var seconds = parseInt(splitTime[1]);        
        
        return ((minutes * 60) + seconds); //converts it all to seconds
    }


    function updateUserList()
    {
        var users;
		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getUsersInRoom", //gets all the users in the room
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) { 
                users = data.d;
                var user = users.split('|');
                document.getElementById("userList").innerHTML='<li>' + user[0] + '</li>' // inserts 5 list items for the users in the room 
                +'<li>' + user[1] + '</li>'
                +'<li>' + user[2] + '</li>'
                +'<li>' + user[3] + '</li>'
                +'<li>' + user[4] + '</li>'; 
            }
		});      
    }


    function updateSongHistoryList()
    {
        var songHistory;
		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getRoomSongHistory", // gets the last 10 song entries added to the database
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) { 
                songHistory = data.d;
                var song = songHistory.split('|');
                document.getElementById("songHistory").innerHTML='<li>' + song[0] + '</li>' // displays them in a list
                +'<li>' + song[1] + '</li>'
                +'<li>' + song[2] + '</li>'
                +'<li>' + song[3] + '</li>'
                +'<li>' + song[4] + '</li>'
                +'<li>' + song[5] + '</li>'
                +'<li>' + song[6] + '</li>'
                +'<li>' + song[7] + '</li>'
                +'<li>' + song[8] + '</li>'
                +'<li>' + song[9] + '</li>'; 
            }
		});
    }


    function getUpdatedSongRating()
    {
        var ratingMessage = "";
		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getUpdatedSongRating", // gets the song rating for the current song playing in the room
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) { 
                ratingMessage = data.d;
                document.getElementById("ratingMessage").innerHTML=ratingMessage; // displays the song rating on the page
            }
		});
    }
    

    // JS function to update the user's rating for the current song
    function updateSongRating()
    {
        
        if(document.getElementById("userRating").value != "") // checks if the box is null
        {
            var songRating = parseInt(document.getElementById("userRating").value);            
            if(!isNaN(songRating)) // if it'd a valid rating
            {
                var isComplete;
                $.ajax({    
			        type: "POST",
			        url: "./../WebService/SongStatus.asmx/updateSongRating",
			        data: "{userID: '"+ userID +"', songID: '"+ songID +"', rating: '"+ songRating +"'}", 
			        contentType: "application/json; charset=utf-8",
			        dataType: "json",                    
                    async: false,
			        success: function (data) { 
                        isComplete = data.d;

                        // if the storeprocedure returns a 1 then it was successful!
                        if (isComplete == 1)
                        {
                            document.getElementById("success").style.visibility='visible';
                            getAvgRating(); // now that we have updated the song rating we get the new average rating for the song
                        }
                        else
                            alert("Song not rated!"); 
                    }			        
		        });

                document.getElementById("userRating").value = '';
            }
            else
                alert("Input must be a number: Please enter a number.");
        }
        else
            alert("Rating field cannot be blank: Please enter a number.");
    }
	

    // vetos the song!
    function vetoSong()
    {
        var isComplete = 0;
        $.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/updateSongRating",
			data: "{userID: '"+ userID +"', songID: '"+ songID +"', rating: '"+ isComplete +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) { 
                isComplete = data.d;
                if (isComplete == 1)
                {
                    document.getElementById("success").style.visibility='visible';
                    document.getElementById("success").innerHTML='Song has been vetoed!';            
                } 
            }
		});
    }


    function getChatComments()
    {        
		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getChatComment",
			data: "{roomID: '"+ roomID +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) { // gets the room chat
                var chatComments = data.d;
                chatComments = chatComments.replaceAll("<apostrophe>", "'"); // fixes the chat apostrophe catastrophe
                document.getElementById("txtChatText").innerHTML=chatComments; 
            }
		});
    }


    function insertChatComment()
    {
        var chatComment = document.getElementById("txtNewChat").value;
        var newChatComment = chatComment.replaceAll("'", "<apostrophe>"); // fixes the chat apostrophe catastrophe
        if(chatComment != '')
        {
            $.ajax({             
			        type: "POST",
			        url: "./../WebService/SongStatus.asmx/insertChatComment",
			        contentType: "application/json; charset=utf-8",
			        dataType: "json",
			        data:  "{userID: '"+ userID +"', roomID: '"+ roomID +"', chatComment: '"+ newChatComment +"'}"
		        });
        }

        document.getElementById("txtNewChat").value = '';
    }


    function insertSongComment()
    {
        var songComment = document.getElementById("txtSongComment").value;
        var newSongComment = songComment.replaceAll("'", "<apostrophe>"); // fixes the song apostrophe catastrophe
        var commentTime = getSongsCurrentTime();
        if(songComment != '')
        {
            $.ajax({             
			        type: "POST",
			        url: "./../WebService/SongStatus.asmx/insertSongComment",
			        contentType: "application/json; charset=utf-8",
			        dataType: "json",
			        data:  "{songID: '"+ songID +"', userID: '"+ userID +"', time: '"+ commentTime +"', songComment: '"+ newSongComment +"'}"
		        });
        }
        document.getElementById("txtSongComment").value = '';
    }


    function getSongComment()
    {        
        var currentTime = getSongsCurrentTime();
		$.ajax({    
			type: "POST",
			url: "./../WebService/SongStatus.asmx/getSongComment",
			data: "{songID: '"+ songID +"', time: '"+ currentTime +"'}", 
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) { // gets the song comment
                var songComment = data.d;
                songComment = songComment.replaceAll("<apostrophe>", "'"); // fixes the song apostrophe catastrophe
                document.getElementById("songComment").innerHTML=songComment; 
            }
		});
    }


    // this little codegem gives a replaceAll function for Javascript since there is no default replacAll function
    String.prototype.replaceAll=function(s1, s2) {return this.split(s1).join(s2)}


	// this function is used for error testing and trouble shooting ajax errors
	function ajaxFailure(ajax) 
    {
		alert("Error making Ajax request:" +
		"\n\nServer status:\n" + ajax.status + " " + ajax.statusText +
		"\n\nServer response text:\n" + ajax.responseText);
	}

//]]>
</script>

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    &nbsp;&nbsp;&nbsp;
     <div class = "LeaveRoom">    
	    <asp:Button ID="bLeave" runat="server" Text="Leave Room" onclick="bLeave_Click" />
    </div>
    <!-- Label for the roomname -->
    <div class = "roomname">
        <asp:Label ID="roomName" runat="server"  />
    </div>    
	<!-- The code here in the body is the framework for how jplayer is viewed on the screen via the css file in the header -->
	<div id="jquery_jplayer_1" class="jp-jplayer" > </div>
		<div id="jp_container_1" class="jp-audio">        
			<div class="jp-type-single">
				<div class="jp-gui jp-interface" >                            
					<ul class="jp-controls">
						<li><a href="javascript:;" class="jp-play" onclick="updateRoomStatus('Play')" tabindex="1">play</a></li>
						<li><a href="javascript:;" class="jp-pause" onclick="updateRoomStatus('Pause')" tabindex="1"></a></li>
						<li><a href="javascript:;" class="jp-next" onclick="updateRoomStatus('Skip')" tabindex="1">skip</a></li> 
						<li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
						<li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
						<li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>
					</ul>
					<div class="jp-progress">
						<div class="jp-seek-bar">
							<div class="jp-play-bar"></div>
						</div>
					</div>
					<div class="jp-volume-bar">
						<div class="jp-volume-bar-value"></div>                        
					</div>
					<div class="jp-time-holder">
						<div id="currentTime" class="jp-current-time"></div>
						<div class="jp-duration"></div>						
					</div>
				</div>
				<div class="jp-title">
					<ul>
						<li><strong id="artist">Artist</strong> - <span id="songname">Songname</span></li> <!-- The Artist name and Song name is displayed dynamically! -->                        
					</ul>
				</div>
				<div class="jp-no-solution">
					<span>Update Required</span>
					To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
				</div>
			</div>
		</div>
    
    
    <p style="color:white;" id="songComment"></p>    
    <h3 style="color:red;">Throw up a comment about the song, hate it, love it, whatever.... <br /> HONEYBADGER DON'T CARE!</h3>    
    <form action="#">
    <input style="float:left; width:425px" type="text" id="txtSongComment" />
    <input style="float:left; " type="submit" id="btnSongComment" value="Send" onclick="insertSongComment(); return false;"/>
    </form><br />

    <form action="#">
    <h2 style="color:red;">Rating</h2>
    <input type="text" id="userRating" />
    <input type="submit" id="btnUpdateSongRating" value="Update Rating" onclick="updateSongRating(); return false;"/>
    <input type="button" id="btnVetoSong" value="Veto Song" onclick="vetoSong()"/>
    </form>	    
    
    <p style="color:red;" id="lblAvgRate">Average Song Rating</p>
    <p style="color:red;visibility:hidden;" id="success" >Song rating has been successfully updated</p>
    <p style="color:red;" id="ratingMessage"></p>    
	   
   <div class ="chat">
   <form action="#">
        <h2 style="color:red;">Room Chat</h2>
        <textarea id="txtChatText" rows="20" cols="40"></textarea>        
        <input style="float:left; width:300px;" type="text" id="txtNewChat" onclick="return txtNewChat_onclick()" />
        <input style="float:left;" type="submit" id="submitChat" value="Send" onclick="insertChatComment()"/>
   </form>        
   </div>

   <div style="float:left;">
    <h2 style="color:red;">Users:</h2>
    <ol id="userList" ></ol>
    </div>	
        
   <div style="float:left;">
   <h2 style="color:red;">Song History:</h2>
   <ol id="songHistory" ></ol>
   </div>

</asp:Content>
